package com.coolpoint.test;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by sheng on 17/5/8.
 */

public class SlideSignatureView extends View {

    private static final String TAG = SlideSignatureView.class.getSimpleName();

    //滑动图片
    private Bitmap mLockBitmap;
    private int mLockDrawableId;

    //圆角角度
    private int mLockRadius;

    /**
     * 滑块当前的状态
     */
    public int currentState;
    /**
     * 未解锁
     */
    public static final int STATE_LOCK = 1;
    /**
     * 解锁
     */
    public static final int STATE_UNLOCK = 2;
    /**
     * 正在拖拽
     */
    public static final int STATE_MOVING = 3;

    /**
     * 滑动的宽度
     */
    private int blockBackgoundWidth;
    /**
     * 滑块宽高
     */
    private int blockWidth;
    private int blockHeight;
    /**
     * 手指在滑块的x，y值
     */
    private float x;
    private float y;
    /**
     * 手指在按下时，是否按到了滑块上
     */
    private boolean downOnBlock;


    private OnSlideListener mListener;


    public SlideSignatureView(Context context) {
        this(context, null);

    }

    public SlideSignatureView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideSignatureView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray tp = context.obtainStyledAttributes(attrs, R.styleable.SlideSignatureView, defStyleAttr, 0);
        mLockDrawableId = tp.getResourceId(R.styleable.SlideSignatureView_lock_drawable, -1);
        mLockRadius = tp.getDimensionPixelOffset(R.styleable.SlideSignatureView_lock_radius, 1);
        tp.recycle();

        if (mLockDrawableId == -1) {
            throw new RuntimeException("未设置滑动图片");
        }

        currentState = STATE_LOCK;
        init(context);

    }

    private void init(Context context) {

        mLockBitmap = BitmapFactory.decodeResource(context.getResources(), mLockDrawableId);
        int oldSize = mLockBitmap.getHeight();
        int width = mLockBitmap.getWidth();
        int newSize = mLockRadius * 2;
        float scale = newSize * 1.0f / oldSize;
        Matrix matrix = new Matrix();
        matrix.setScale(scale, scale);
        mLockBitmap = Bitmap.createBitmap(mLockBitmap, 0, 0, width, oldSize, matrix, true);

        // 获取滑块的宽和高
        blockWidth = mLockBitmap.getWidth();
        blockHeight = mLockBitmap.getHeight();
    }


    public void setOnSlideListener(OnSlideListener mListener) {
        this.mListener = mListener;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        blockBackgoundWidth = this.getWidth();
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        /**
         * 判断当前状态
         */
        switch (currentState) {
            // 如果是未解锁，就将滑块绘制到最左端
            case STATE_LOCK:
                canvas.drawBitmap(mLockBitmap, 0, 0, null);
                break;
            // 已解锁，计算出
            case STATE_UNLOCK:
                int unlockX = blockBackgoundWidth - blockWidth;
                canvas.drawBitmap(mLockBitmap, unlockX, 0, null);
                break;
            case STATE_MOVING:
                if (x < 0) {
                    x = 0;
                } else if (x > blockBackgoundWidth - blockWidth) {
                    x = blockBackgoundWidth - blockWidth;
                }
                canvas.drawBitmap(mLockBitmap, x, 0, null);
                break;
            default:
                break;
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            // 当手指按下的时候，判断手指按下的位置是否在滑块上边
            case MotionEvent.ACTION_DOWN:

                if (currentState != STATE_MOVING) {
                    // 判断一下，如果当前正在移动，则不执行触摸操作
                    // 获取相对于背景的左上角的x，y值
                    x = event.getX();
                    y = event.getY();
                    // 先计算出滑块的中心点的x，y坐标
                    float blockCenterX = blockWidth * 1.0f / 2;
                    float blockCenterY = blockHeight * 1.0f / 2;
                    downOnBlock = isDownOnBlock(blockCenterX, x, blockCenterY, y);
                    Log.i(TAG, "down......................");
                    // 调用onDraw方法
                    postInvalidate();

                }
                break;
            case MotionEvent.ACTION_MOVE:
                // 如果手指确定按在滑块上，就视为开始拖拽滑块
                if (downOnBlock) {
                    // 获取相对于背景的左上角的x，y值
                    x = event.getX();
                    y = event.getY();
                    currentState = STATE_MOVING;
                    Log.i(TAG, "move......................");
                    // 调用onDraw方法
                    postInvalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                if (currentState == STATE_MOVING) {
                    // 当手指抬起的时候，应该是让滑块归位的
                    // 说明未解锁
                    Log.e("ACTION_UP----> ","手指抬起");
                    if (x < blockBackgoundWidth - blockWidth) {
                        handler.sendEmptyMessageDelayed(0, 10);
                    } else {
                        currentState = STATE_UNLOCK;
                        // 通过回调设置未解锁
                        Log.e("终点----> ", "true");
                        if (mListener != null) {
                            mListener.slideSuccess();
                        }
                    }
                    downOnBlock = false;
                    // 调用onDraw方法
                    postInvalidate();

                }
                break;

            default:
                break;
        }
        return true;
    }


    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                // 如果x还大于0，就人为的设置缓慢移动到最左端，每次移动距离设置为背景宽的/100
                if (x > 0) {
                    x = x - blockBackgoundWidth * 1.0f / 100;
                    // 刷新界面
                    postInvalidate();
                    // 设置继续移动
                    handler.sendEmptyMessageDelayed(0, 10);
                } else {
                    handler.removeCallbacksAndMessages(null);
                    currentState = STATE_LOCK;
                    Log.i(TAG, "state---lock.....");
                }
            }
        }
    };


    /**
     * 计算手指是否是落在了滑块上(默认是按照滑块在未解锁的初始位置来计算的)
     */
    public boolean isDownOnBlock(float x1, float x2, float y1, float y2) {
        float sqrt = (float) Math.sqrt(Math.abs(x1 - x2) * Math.abs(x1 - x2)
                + Math.abs(y1 - y2) * Math.abs(y1 - y2));
        if (sqrt <= blockWidth / 2) {
            return true;
        }
        return false;
    }


    public interface OnSlideListener {
        void slideSuccess();
    }

}
